package com.sky.aspect;

import com.sky.annotate.AutoFill;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import com.sky.exception.BaseException;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.time.LocalDateTime;


@Aspect
@Component
public class AutoAspect {
    @Pointcut("execution(* com.sky.mapper.*.*(..))&&@annotation(com.sky.annotate.AutoFill)")
    public void PointCut() {
    }

    @Before("PointCut()")
    public void AutoFill(JoinPoint joinPoint) {
        //第1步 获得方法上的注解
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        AutoFill annotation = signature.getMethod().getAnnotation(AutoFill.class);
        OperationType value = annotation.value();


        //第2步 获得方法的参数 也就是实体类对象
        Object[] args = joinPoint.getArgs();
        Object arg = args[0];

        try {
            //第3步 通过反射获得公共字段的set方法/属性 这里我使用属性吧 方法写过了
            Field createTime = arg.getClass().getDeclaredField("createTime");
            Field updateTime = arg.getClass().getDeclaredField("updateTime");
            Field createUser = arg.getClass().getDeclaredField("createUser");
            Field updateUser = arg.getClass().getDeclaredField("updateUser");
            if (value == OperationType.INSERT) {
                createTime.setAccessible(true);
                updateTime.setAccessible(true);
                createUser.setAccessible(true);
                updateUser.setAccessible(true);
                createTime.set(arg, LocalDateTime.now());
                updateTime.set(arg, LocalDateTime.now());
                createUser.set(arg, BaseContext.getCurrentId());
                updateUser.set(arg, BaseContext.getCurrentId());
            } else {
                updateTime.setAccessible(true);
                updateUser.setAccessible(true);
                updateTime.set(arg, LocalDateTime.now());
                updateUser.set(arg, BaseContext.getCurrentId());
            }
        } catch (Exception ex) {
            throw new BaseException(MessageConstant.AUTO_FILL_FAILED);
        }

    }
}
